<script setup lang="ts">
import { ref } from 'vue'
import http from '../utils/http'
import { message } from '../utils/message'
import { NCard, NSpace, NButton, NInput, NSpin, NCode } from 'naive-ui'

const loading = ref(false)
const url = ref('https://api.github.com/users/github')
const response = ref<string>('')

async function handleGet(): Promise<void> {
  loading.value = true
  response.value = ''
  try {
    const res = await http.get(url.value)
    response.value = JSON.stringify(res.data, null, 2)
    message.success('请求成功')
  } catch (error) {
    response.value = `错误: ${(error as Error).message}`
  } finally {
    loading.value = false
  }
}

async function handlePost(): Promise<void> {
  loading.value = true
  response.value = ''
  try {
    const res = await http.post('https://httpbin.org/post', {
      name: 'test',
      timestamp: Date.now()
    })
    response.value = JSON.stringify(res.data, null, 2)
    message.success('请求成功')
  } catch (error) {
    response.value = `错误: ${(error as Error).message}`
  } finally {
    loading.value = false
  }
}

async function handleTimeout(): Promise<void> {
  loading.value = true
  response.value = ''
  try {
    await http.get('https://httpbin.org/delay/15', { timeout: 2000 })
  } catch (error) {
    response.value = `错误: ${(error as Error).message}`
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <n-card title="HTTP 请求示例" class="max-w-800px mx-auto mt-8">
    <n-space vertical :size="16">
      <!-- URL 输入 -->
      <n-input v-model:value="url" placeholder="请输入 URL" />

      <!-- 操作按钮 -->
      <n-space>
        <n-button type="primary" :loading="loading" @click="handleGet">GET 请求</n-button>
        <n-button :loading="loading" @click="handlePost">POST 请求</n-button>
        <n-button :loading="loading" @click="handleTimeout">超时测试</n-button>
      </n-space>

      <!-- 响应结果 -->
      <div v-if="loading" class="flex justify-center py-8">
        <n-spin size="large" />
      </div>

      <div v-else-if="response" class="mt-4">
        <p class="text-sm text-gray-600 mb-2">响应结果</p>
        <n-code :code="response" language="json" class="max-h-400px overflow-auto" />
      </div>
    </n-space>
  </n-card>
</template>
